package com.jy.rhin.domain.notification.publish.entity;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * @author WeiQ
 * @date 2022/6/29 8:52
 * 派发的消息
 */
@Data
@NoArgsConstructor
public class PublishMessageDO {

    public PublishMessageDO(SubscribeAndFilterVO vo) {
        this.publisherCode = vo.getPublisherCode();
        this.publisherName = vo.getPublisherName();
        this.subscriberCode = vo.getSubscriberCode();
        this.subscriberName = vo.getSubscriberName();
        this.topicId = vo.getTopicId();
        this.subscribeId = vo.getSubscribeId();
    }

    public PublishMessageDO init(Long messageId) {
        this.createTime = new Date();
        this.notifyStatus = EnumPublishMessageNotifyStatus.INIT;
        this.publishCount = 0;
        this.messageId = messageId;
        return this;
    }

    /**
     * 发布消息通知订阅者成功，更新发布消息状态
     * 已经发布成功的消息，忽略本次发送失败记录
     *
     * @return
     */
    public boolean publishSuccess() {
        if (this.notifyStatus == EnumPublishMessageNotifyStatus.DONE) {
            return false;
        }
        this.publishCount += 1;
        this.notifyTime = new Date();
        this.notifyStatus = EnumPublishMessageNotifyStatus.DONE;
        this.result = true;
        return true;
    }

    /**
     * 发布消息通知订阅者失败，更新发布消息状态
     * 已经发布成功的消息，忽略本次发送失败记录
     *
     * @param resultDesc
     * @return
     */
    public boolean publishFail(String resultDesc) {
        if (this.notifyStatus == EnumPublishMessageNotifyStatus.DONE) {
            return false;
        }
        this.publishCount += 1;
        this.notifyTime = new Date();
        this.resultDesc = resultDesc;
        this.result = false;
        return true;
    }

    private Long id;
    /**
     * 通知消息记录表主键id
     */
    private Long messageId;
    /**
     * 发布者
     */
    private String publisherCode;
    private String publisherName;
    /**
     * 订阅者
     */
    private String subscriberCode;
    private String subscriberName;
    /**
     * 主题id
     */
    private Long topicId;
    /**
     * 订阅id
     */
    private Long subscribeId;
    /**
     * 通知状态;INIT:初始化,DONE:已完成
     */
    private EnumPublishMessageNotifyStatus notifyStatus;
    /**
     * 发送次数：第一次发送开始计数，如果发送失败，没重试一次，计数加1
     */
    private Integer publishCount;
    /**
     * 通知时间;最后一次发送通知的时间,不论成功或失败
     */
    private Date notifyTime;
    /**
     * 创建时间
     */
    private Date createTime;
    /**
     * 发布消息结果
     */
    private Boolean result;
    /**
     * 发布消息结果说明
     */
    private String resultDesc;

}
